//
//  JROAthViewController.swift
//  swiftWeiBo
//
//  Created by Johnray on 15/9/23.
//  Copyright © 2015年 Johnray. All rights reserved.
//

import UIKit

class JROAthViewController: UIViewController {

    
    private lazy var webView = UIWebView()
    
    override func loadView() {
        
        view = webView
        
        webView.delegate = self
        
        title = "授权登陆"
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //view.backgroundColor = UIColor.redColor()
        
        
        
        let request:NSURLRequest = NSURLRequest(URL: JRNetWorkTools.shareNetWorkTools.oathurl)
        
        webView.loadRequest(request)
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        

    }
    
    //出栈
    @objc private func dismiss(){
    
        navigationController?.dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    /**
    * 自动填充
    */
    @objc private func autoFill(){
        
        let js = "document.getElementById('userId').value = 'daoge10000@sina.cn';" +
        "document.getElementById('passwd').value = 'qqq123';"
        
        // 让 webView 执行 js
        webView.stringByEvaluatingJavaScriptFromString(js)
    
    }
    
    
}


//MARK: - webview代理方法
extension JROAthViewController:UIWebViewDelegate{
    
     func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //请求地址开头是否包含www.baidu.com
        if !request.URL!.absoluteString.hasPrefix(JRNetWorkTools.shareNetWorkTools.httpAddress) {
        
            return true
        
        }
//        print("asdas",request.URL?.absoluteString)
//        
//        print(request.URL?.query)
        
        //获得token
        if let query = request.URL?.query where query.hasPrefix("code="){
        
            let code = query.substringFromIndex("code=".endIndex)
            
            
            JRNetWorkTools.shareNetWorkTools.loadUserAccessToken(code, finshed: { (success, error) -> () in
                
                if error != nil{
                    print("出错了-- \(error)")
                    return
                }
                
                let userAccount = JRUserAccount(dict: success as! [String:AnyObject])
                
                
                print(userAccount)
            })
            
        }
        
        
        
        dismiss()
        return false
    }
    
    
    
    
}
